/*
 * @Author: ziqi jhzq12345678
 * @Date: 2024-08-28 10:02:57
 * @LastEditors: ziqi jhzq12345678
 * @LastEditTime: 2025-01-07 15:59:31
 * @FilePath: /pornhub_app/lib/src/components/announcement/announcement.dart
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

import 'package:get/get.dart';
import 'package:pornhub_app/components/image_view.dart';
import 'package:pornhub_app/http/http_service.dart';
import 'package:pornhub_app/model/activity/activity_model.dart';
import 'package:pornhub_app/model/advertisements/app_update.dart';
import 'package:pornhub_app/model/announcement/announcement.dart';
import 'package:pornhub_app/model/announcement/home_activity.dart';

import 'package:pornhub_app/utils/ad_jump.dart';
import 'package:pornhub_app/utils/color.dart';
import 'package:pornhub_app/utils/context_link.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:pornhub_app/utils/enum.dart';
import 'package:pornhub_app/utils/extension.dart';
import 'package:pornhub_app/utils/initAdvertisementInfo.dart';
import 'package:pornhub_app/utils/logger.dart';
import '../../services/app_service.dart';
import 'update_dialog.dart';

// ValueNotifier<double> progress = ValueNotifier(0);
/// android内更新
// Future _androidInnerAppDownloadApk(String apkURL) async {
//   if (apkURL.isEmpty) {
//     EasyToast.show('下载链接非法！');
//     return;
//   }

//   // SmartDialog.showLoading(msg: "下载中:0%", alignment: Alignment.center);
//   final res = await filedownloader.downloadMediaFile(apkURL,
//       onProgress: (count, total) {
//     progress.value = (count / total) * 100.0.toDouble();
//     // SmartDialog.showLoading(msg: "下载中:$percent%", alignment: Alignment.center);
//   });
//   SmartDialog.dismiss();
//   if (res == FileDownloaderResult.fail) {
//     EasyToast.show("下载失败，请重试!");
//     return;
//   }
//   if (res == FileDownloaderResult.success) {
//     final filePath = await filedownloader.fileSavePathForNative(apkURL);
//     final insRes = await InstallPlugin.install(filePath);
//     EasyToast.show(insRes['isSuccess'] == true
//         ? '安装成功'
//         : '安装失败:${insRes['errorMessage'] ?? ''}');
//     return;
//   }
// }

void showAnn() async {
  ValueNotifier<int> acitveIdx = ValueNotifier(0);
  List<Widget> dialoglist = [];

  // ignore: no_leading_underscores_for_local_identifiers
  Widget _annDialog(ann) {
    return Container(
      width: 280.w,
      height: 320.w,
      decoration: BoxDecoration(
          image:
              const DecorationImage(image: AssetImage('assets/ann/ann_bg.png')),
          borderRadius: BorderRadius.circular(10.w)),
      child: Flex(
        direction: Axis.vertical,
        children: [
          SizedBox(
            height: 76.w,
          ),
          Expanded(
              child: Container(
            height: 198.w,
            padding: EdgeInsets.only(left: 14.w, right: 14.w),
            child: SingleChildScrollView(
              child: Text.rich(
                  TextSpan(
                      children: contextLink(
                          ann.content ?? '',
                          TextStyle(
                              color: COLOR.hexColor('#eb29c6'),
                              fontSize: 14.w))),
                  style:
                      TextStyle(color: COLOR.hexColor('#333'), fontSize: 12.w)),
            ),
          )),
          SizedBox(
            width: 280.w,
            height: 46.w,
            child: Row(
              children: [
                Image.asset(
                  'assets/ann/ic_cancle.png',
                  width: 140.w,
                  height: 46.w,
                ).onTap(() {
                  if (acitveIdx.value == dialoglist.length - 1) {
                    SmartDialog.dismiss();
                  } else {
                    acitveIdx.value += 1;
                  }
                }),
                Image.asset(
                  'assets/ann/ann_tj.png',
                  width: 140.w,
                  height: 46.w,
                )
              ],
            ),
          ),
        ],
      ),
    );
  }

  // ignore: no_leading_underscores_for_local_identifiers
  Widget _annActivity(ActivityModel activity) {
    return Container(
      width: 200.w,
      height: 350.w,
      alignment: Alignment.center,
      margin: EdgeInsets.all(20.w),
      padding: EdgeInsets.only(bottom: 16.w),
      child: Column(
        children: [
          ValueListenableBuilder(
              valueListenable: acitveIdx,
              builder: (context, value, index) {
                return GestureDetector(
                  onTap: () {
                    kAdjump(activity.actUrl, activity.actId);
                    if (activity.actUrl!.contains('activity')) {
                      SmartDialog.dismiss();
                    }
                  },
                  child: ImageView(
                    src: activity.coverPicture ?? '',
                    width: 200.w,
                    height: 250.w,
                    fit: BoxFit.fill,
                  ),
                );
              }),
          Padding(padding: EdgeInsets.only(bottom: 10.w)),
          GestureDetector(
            onTap: () {
              if (acitveIdx.value == dialoglist.length - 1) {
                SmartDialog.dismiss();
              } else {
                acitveIdx.value += 1;
              }
            },
            child: Icon(
              size: 40.w,
              Icons.cancel,
              color: Colors.white,
            ),
          )
        ],
      ),
    );
  }

  // ignore: no_leading_underscores_for_local_identifiers
  Widget _updateDialog(updates) {
    return Container(
      width: 280.w,
      height: 343.w,
      decoration: BoxDecoration(
          image:
              const DecorationImage(image: AssetImage('assets/ann/up_bg.png')),
          borderRadius: BorderRadius.circular(10.w)),
      child: Flex(
        direction: Axis.vertical,
        children: [
          SizedBox(
            height: 57.w,
          ),
          Text(
            '${updates.versionNum}版本更新',
            style: TextStyle(
                color: COLOR.hexColor('#000000'),
                fontSize: 25.w,
                fontWeight: FontWeight.w600),
          ),
          SizedBox(
            height: 45.w,
          ),
          Expanded(
              child: Container(
            height: 195.w,
            padding: EdgeInsets.only(left: 14.w, right: 14.w),
            child: SingleChildScrollView(
              child: Text.rich(
                  TextSpan(
                      children: contextLink(
                          updates.info ?? '',
                          TextStyle(
                              color: COLOR.hexColor('#eb29c6'),
                              fontSize: 14.w))),
                  style:
                      TextStyle(color: COLOR.hexColor('#333'), fontSize: 12.w)),
            ),
          )),
          SizedBox(
            width: 280.w,
            height: 46.w,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image.asset(
                  'assets/ann/ic_cancle.png',
                  width: 140.w,
                  height: 46.w,
                ).onTap(() {
                  if (updates.isForceUpdate) return;
                  if (acitveIdx.value == dialoglist.length - 1) {
                    SmartDialog.dismiss();
                  } else {
                    acitveIdx.value += 1;
                  }
                }),
                Image.asset(
                  'assets/ann/ic_update.png',
                  width: 140.w,
                  height: 46.w,
                ).onTap(() async {
                  if (updates is AppUpdateModel) {
                    // final apkURL = updates.link ?? '';
                    // _androidInnerAppDownloadApk(apkURL);
                    final url = Get.find<AppService>().androidLandURL;
                    jumpExternalAddress(url ?? '', null);
                  }
                })
              ],
            ),
          ),
        ],
      ),
    );
  }

  final iconAds = initSequenceAdvertisementInfo(AdPlaceNameEnum.NDD_BANNER);

  // ignore: no_leading_underscores_for_local_identifiers
  Widget _adDialog() {
    var length = iconAds.length;
    double initHeight() {
      if (length < 5) return 175.w;
      if (length < 9) return 300.w;
      if (length < 13) return 415.w;
      return 490.w;
    }

    return Container(
      width: 360.w,
      constraints: BoxConstraints(maxHeight: initHeight()),
      alignment: Alignment.center,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        mainAxisSize: MainAxisSize.min,
        children: [
          Expanded(
              child: SingleChildScrollView(
                  child: Wrap(
            spacing: 20.w,
            runSpacing: 0.w,
            children: iconAds.map((v) {
              return SizedBox(
                width: 75.w,
                height: 115.w,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    ImageView(
                      src: v.adImage!,
                      width: 75.w,
                      height: 75.w,
                    ),
                    Padding(padding: EdgeInsets.only(bottom: 5.w)),
                    Container(
                      padding: EdgeInsets.symmetric(vertical: 5.w),
                      child: Text(
                        '${v.adName}',
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(color: Colors.white, fontSize: 13.w),
                      ),
                    )
                  ],
                ).onOpaqueTap(() {
                  kAdjump(v, v.adId);
                }),
              );
            }).toList(),
          ))),
          Padding(padding: EdgeInsets.only(bottom: 20.w)),
          GestureDetector(
            onTap: () {
              if (acitveIdx.value == dialoglist.length - 1) {
                SmartDialog.dismiss();
              } else {
                acitveIdx.value += 1;
              }
            },
            child: Icon(
              Icons.cancel,
              color: Colors.white,
              size: 40.w,
            ),
          ),
        ],
      ),
    );
  }

  AppUpdateModel? update;
  //系统更新
  if (!kIsWeb) {
    try {
      update = await checkVersion();
      logger.d('update:${update != null}');
      if (update != null) {
        dialoglist.add(showUpdateDialog(update));
      }
    } catch (_) {
      logger.e(_);
    }
  }
  //公告
  final ann = await httpInstance.get<AnnouncementModel>(
      url: 'sys/ann', complete: AnnouncementModel.fromJson);
  if (ann != null) {
    dialoglist.add(_annDialog(ann));
  }
  if (iconAds.isNotEmpty) {
    dialoglist.add(_adDialog());
  }

  //活动
  final activity = await httpInstance.get<HomeActivityModel>(
      url: 'activity/indexActs', complete: HomeActivityModel.fromJson);
  final List<ActivityModel> actList = activity.actList ?? [];

  if (actList.isNotEmpty) {
    List<Widget> images = actList.map((v) => _annActivity(v)).toList();
    dialoglist.addAll(images);
  }

  stackDialog({
    bool clickMaskDismiss = false,
    double width = double.infinity,
    double height = double.infinity,
  }) async {
    SmartDialog.show(
        maskColor: const Color.fromRGBO(0, 0, 0, 0.5),
        builder: (_) {
          return ValueListenableBuilder(
              valueListenable: acitveIdx,
              builder: (context, value, child) {
                return dialoglist[value];
              });
        },
        clickMaskDismiss: clickMaskDismiss,
        onMask: () {
          if ((!kIsWeb &&
              update != null &&
              update.hasNewVersion! &&
              update.isForceUpdate!)) {
            return;
          }
          if (acitveIdx.value == dialoglist.length - 1) {
            SmartDialog.dismiss();
          } else {
            acitveIdx.value += 1;
          }
        });
  }

  if (dialoglist.isEmpty) return;
  await stackDialog();
}
